﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using SharpSoda.Message;

namespace SharpSoda.Storage
{
    public class LocalStateStorage<TState> : IStateStorage
        where TState : class
    {
        protected Dictionary<string, TState> m_States = new Dictionary<string, TState>();

        public virtual ulong SetState<T>(string objectName, T state, ulong flag = 0) where T : class
        {
            if (flag == 0 || objectName == null || state == null || !(state is TState)) return 1;
            lock (m_States)
            {
                if (!m_States.ContainsKey(objectName)) m_States.Add(objectName, state as TState);
            }
            return 0;
        }

        public virtual ulong GetState<T>(string objectName, out T state, ulong flag = 0) where T : class
        {
            state = null;
            if (objectName == null) return 0;
            lock (m_States)
            {
                if (m_States.ContainsKey(objectName)) state = m_States[objectName] as T;
            }
            return 0;
        }

        public virtual List<T> GetStates<T>(params object[] filters) where T : class
        {
            List<T> result = new List<T>();
            if (filters != null && filters.Length >= 2)
            {
                string name = filters[0] == null ? null : filters[0].ToString();
                object value = filters[1];

                if (name != null && value != null)
                {
                    foreach (var item in m_States)
                    {
                        if (value.Equals(JsonHelper.GetPropertyValue(item.Value, name)))
                        {
                            result.Add(item.Value as T);
                        }
                    }
                }
            }
            return result;
        }

        public virtual T RemoveState<T>(string objectName) where T : class
        {
            T state = null;
            if (objectName == null) return null;
            lock (m_States)
            {
                if (m_States.ContainsKey(objectName))
                {
                    state = m_States[objectName] as T;
                    m_States.Remove(objectName);
                }
            }
            return state;
        }

    }
}
